<?php

class Adept_Db_Config
{

    private $driver;
    private $host;
    private $user;
    private $password;
    private $database;
    private $charset;

    /**
     * <pre>
     * $config = new Adept_Db_Config('MySql://foo:bar@localhost/abc?charset=cp1252');
     * </pre>
     * @param string $connectionString default null
     */
    public function __construct($connectionString = null)
    {
        if (!is_null($connectionString)) {
            $this->parse($connectionString);
        }
    }

    /**
     * <pre>
     * $config = new Adept_Db_Config('MySql://foo:bar@localhost/abc?charset=cp1252');
     * </pre>
     *
     * @param string $connectonString
     */
    public function parse($connectionString)
    {
        $parts = @parse_url($connectionString);
        if (!$parts) {
            throw new Adept_Db_Exception('Invalid connection string syntax: ' . $connectionString);
        }

        $this->driver   = isset($parts['scheme']) ? $parts['scheme'] : '';
        $this->host     = isset($parts['host']) ?   $parts['host'] : '';
        $this->user     = isset($parts['user']) ?   $parts['user'] : '';
        $this->password = isset($parts['pass']) ?   $parts['pass'] : '';
        $this->database = isset($parts['path']) ?   trim($parts['path'], '/') : '';

        $query = isset($parts['query']) ? $parts['query'] : '';
        if ($query) {
            parse_str($query, $parameters);
            $this->charset = isset($parameters['charset']) ? $parameters['charset'] : '';
        } else { 
            $this->charset = '';
        }
    }

    public function getDriver()
    {
        return $this->driver;
    }

    public function getDriverClassName()
    {
        return 'Adept_Db_' . $this->getDriver() . '_Connection';
    }

    public function getHost() 
    {
        return $this->host;
    }

    public function getUser() 
    {
        return $this->user;
    }

    public function getPassword() 
    {
        return $this->password;
    }

    public function getDatabase() 
    {
        return $this->database;
    }

    public function getCharset() 
    {
        return $this->charset;
    }

    public function __toString()
    {
        return $this->getDriver() . '://' . $this->getUser() . ':_PASSWORD_@'
            . $this->getHost() . '/' . $this->getDatabase();
    }

}